<?php
class cmsdream_login {

	public static function submit($url, $params){
		$_url = parse_url($url);
		$_host = $_url['host'];
		$_scheme = $_url['scheme'];
		$_port = $_scheme == 'http' ? '80' : '443';
		$header = "POST $url HTTP/1.1\r\n";
		$header .= "Host:$_host:$_port\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($params) . "\r\n";
		$header .= "Connection: Close\r\n\r\n";
		$header .= $params;
		$fp = fsockopen($_host, $_port);
		fputs($fp, $header);
		$rst = new stdClass();
		$rst->cookie = array();
		$key=0;
		while(!feof($fp)) {
			$str = fgets($fp);
			if(preg_match('/^HTTP\/1\.1\s+([\d]+)\s+(.*)$/i', $str, $s)){
				$rst->status = array('number'=>$s[1],'text'=>$s[2]);
			}
			if(preg_match('/_wpnonce=([a-zA-Z0-9]{10})/i', $str, $n)){
				$rst->_wpnonce = $n[1];
			}
			if(preg_match('/^<div\s+id="login_error">(.*)$/i', $str, $g)){
				$msg = preg_replace('/<a[^>]+>(.*)<\/a>/i', '', trim($g[1]));
				$rst->message = $msg;
			}
			if(preg_match('/^Set\-Cookie\:(.*)/i', $str, $m)){
				if(preg_match_all('/([\w]+)\=([^;]+)/i', trim($m[1]), $kv)){	
					$rst->cookie[$key]['name'] = $kv[1][0];
					$rst->cookie[$key]['value'] = urldecode($kv[2][0]);				
					for($i=1;$i<count($kv[0]);$i++){
						$rst->cookie[$key][$kv[1][$i]] = urldecode($kv[2][$i]);
					}
					$key++;
				}
			}
		}
		fclose($fp);
		return $rst;
	}
	
	public static function save_sc($arr){
		foreach($arr as $row){
			if(isset($row['name']) && isset($row['value'])){
				$name = $row['name'];
				$value = $row['value'];
				$expires = isset($row['expires']) ? (is_numeric($row['expires']) ? $row['expires'] : strtotime($row['expires'])) : (time()+3600*24*7);
				$path = isset($row['path']) ? $row['path'] : '/';
				if(!setcookie($name, $value, $expires, $path)){
					$_SESSION[$name] = $value;
				}
			}
		}
	}
	
	public static function get_sc($name, $def=NULL){
		$ss = isset($_COOKIE[$name]) ? $_COOKIE[$name] : (isset($_SESSION[$name]) ? $_SESSION[$name] : '');
		return (!empty($def) && $ss=='') ? $def : $ss;
	}
	
	public function __construct() {
		
	}
	
	public function __destruct(){
	
	}
	
}

